﻿Friend Class FRestoreFiles
    Private mFilesCompleted As Integer = 0
    Private mFilesTotal As Integer = 0
    Private mSizeCompleted As Long = 0
    Private mSizeTotal As Long = 0
    Private mSizeDivider As Integer = 1

    Private WithEvents mRestoreTask As Engine.RestoreTask
    Private mRequest As Engine.RestoreRequest

    Public Shadows Sub Show(ByVal owner As Form, ByVal request As Engine.RestoreRequest)
        mRequest = request
        mFilesTotal = request.Files.Count

        mSizeTotal = 0
        For Each clsFile As Entities.Backup.BackedUpFileContainerInfo In request.Files
            mSizeTotal += clsFile.FileSize
        Next
        CalcSizeDivider()

        lblOverAllProgress.Tag = lblOverAllProgress.Text
        pgbOverAll.Minimum = 0
        pgbOverAll.Maximum = CInt(mSizeTotal / mSizeDivider)
        UpdateProgress()
        StartWorking()
        MyBase.Show()
    End Sub

    Private Sub CalcSizeDivider()
        While mSizeTotal / mSizeDivider > Integer.MaxValue
            mSizeDivider *= 10
        End While
    End Sub

    Private Sub UpdateProgress()
        Dim strOverAll As String = String.Format(CStr(lblOverAllProgress.Tag), mFilesCompleted, mFilesTotal, Framework.Misc.ToReadableFileSize(mSizeCompleted), Framework.Misc.ToReadableFileSize(mSizeTotal))
        If lblOverAllProgress.Text <> strOverAll Then lblOverAllProgress.Text = strOverAll

        Dim iSizeProgress As Integer = CInt(mSizeTotal / mSizeDivider)
        If pgbOverAll.Value <> iSizeProgress Then pgbOverAll.Value = iSizeProgress
    End Sub

    Private Sub StartWorking()
        mRestoreTask = Engine.Manager.StartRestoreTask(mRequest)
    End Sub

    Private Sub FRestoreFiles_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    End Sub

    Private Sub mRestoreTask_CompletedGUI(ByVal sender As Engine.RestoreTask) Handles mRestoreTask.CompletedGUI
        btnCancel.Text = "Close"
        mRestoreTask = Nothing
    End Sub

    Private Sub mRestoreTask_ProgressGUI(ByVal sender As Engine.RestoreTask, ByVal e As Engine.RestoreTask.ProgressEventArgs) Handles mRestoreTask.ProgressGUI
        Try
            mFilesCompleted = e.CurrentFileIndex
            UpdateProgress()
        Catch ex As Exception
            Framework.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        If mRestoreTask Is Nothing Then
            Me.Close()
        Else
            mRestoreTask.Abort()
            btnCancel.Text = "Close"
            mRestoreTask = Nothing
        End If
    End Sub
End Class

